<template>
  <a-space :size="22" direction="vertical" fill>
    <div class="editable-item">
      <div class="editable-item-title">企业信息</div>
      <div class="editable-item-content">
        <page-form layout="vertical">
          <page-form-item label="企业名称" required>
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epName" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="注册地址">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epAddress" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="车辆规模">
            <a-input
              @click="disableInputClickFn"
              :model-value="enterpriseDetail.vehicleScale ? enterpriseDetail.vehicleScale + ' 辆' : ''"
              placeholder="请输入"
              disabled
            />
          </page-form-item>
          <page-form-item label="统一社会信用代码">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.uniformSocialCreditCode" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="法人姓名">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epLegalPerson" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="法人身份证号">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epLegalPersonIdCard" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="营业执照有效期" style="margin-bottom: 0" wrap>
            <i-range-picker
              v-if="enterpriseDetail.businessLicenseStartDate"
              disabled
              @click="disableInputClickFn"
              :placeholder="getLicenseRangePlaceholderFn()"
              style="width: 100%"
            />
            <a-input v-else @click="disableInputClickFn" :model-value="'-'" disabled />
          </page-form-item>
        </page-form>
      </div>
    </div>
    <div class="editable-item">
      <div class="editable-item-title">证件资质</div>
      <div class="editable-item-content flex">
        <a-space :size="16">
          <UploadImg
            @click="disableInputClickFn"
            disabled
            :single="true"
            :modelValue="enterpriseDetail.businessLicenseFileId"
            title="营业执照"
          />
          <UploadImg
            @click="disableInputClickFn"
            disabled
            :single="true"
            :modelValue="enterpriseDetail.leaseQualificationFileId"
            title="租赁资质"
          />
        </a-space>
      </div>
    </div>
    <div class="editable-item">
      <div class="editable-item-title">企业负责人</div>
      <div class="editable-item-content">
        <page-form layout="vertical">
          <page-form-item label="负责人姓名" required style="margin-bottom: 0">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epDirector" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="负责人手机号" required style="margin-bottom: 0">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epPhoneNo" placeholder="请输入" disabled />
          </page-form-item>
          <page-form-item label="负责人邮箱" required style="margin-bottom: 0">
            <a-input @click="disableInputClickFn" :model-value="enterpriseDetail.epEmail" placeholder="请输入" disabled />
          </page-form-item>
        </page-form>
      </div>
    </div>
    <div class="editable-item">
      <div class="editable-item-title">其他联系人</div>
      <div class="editable-item-content">
        <page-form layout="vertical" ref="formRef" :model="form">
          <div class="page-form-block">
            <div class="contact-item" v-for="(item, index) in form.epContacts" :key="index">
              <page-form-row>
                <page-form-item :field="`epContacts.${index}.contactJob`" :label="index == 0 ? '职务' : ''" :rules="epLegalPersonRule">
                  <a-input :max-length="20" v-model="item.contactJob" placeholder="请输入" />
                </page-form-item>
                <page-form-item
                  :field="`epContacts.${index}.contactName`"
                  :label="index == 0 ? '联系人姓名' : ''"
                  :rules="epLegalPersonRule"
                >
                  <a-input :max-length="20" v-model="item.contactName" placeholder="请输入" />
                </page-form-item>
                <page-form-item
                  :field="`epContacts.${index}.contactPhone`"
                  :label="index == 0 ? '联系人手机号' : ''"
                  :rules="contactPhoneRule"
                >
                  <a-input v-model="item.contactPhone" placeholder="请输入" />
                </page-form-item>
              </page-form-row>
              <div class="operate-list flex">
                <a-popconfirm v-if="form.epContacts.length > 1" type="warning" content="是否确认删除？" @ok="delEpContactFn(index)">
                  <a-button type="text" class="operate-btn del">
                    <a-space size="mini"><icon-minus-circle />删除</a-space>
                  </a-button>
                </a-popconfirm>
                <a-button type="text" class="operate-btn new" @click="newEpContactFn" v-if="index == form.epContacts.length - 1">
                  <a-space size="mini"><icon-plus-circle />新增</a-space>
                </a-button>
              </div>
            </div>
          </div>
        </page-form>
      </div>
    </div>
  </a-space>
</template>

<script setup name="EnterpriseBasicInfoEdit">
  import { ref, reactive, watch } from 'vue'
  import { isMobile } from '@/utils/validate.js'
  import { saveEnterprise } from '@/api/asset/enterprise.js'
  import { Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  const props = defineProps({
    enterpriseDetail: Object,
  })
  // 联系人数组
  const defaultContacts = {
    contactJob: '',
    contactName: '',
    contactPhone: '',
  }
  const form = reactive({
    epId: '',
    userServiceTypes: [],
    userShortRentChannels: [],
    userWxNativePay: '',
    epContacts: [],
  })
  const validateFn = (value, cb) => {
    if (!value || value == '') {
      cb()
    } else {
      if (!isMobile(value)) {
        cb('手机号格式不正确')
      }
    }
  }
  const validateEpLegalPerson = (value, cb) => {
    if (value == '') {
      cb()
    } else {
      const reg = /^[\u4e00-\u9fa5a-zA-Z]{0,}$/
      if (!reg.test(value)) {
        cb('不能含有数字或符号')
      } else {
        cb()
      }
    }
  }
  const contactPhoneRule = [{ required: false, validator: validateFn, trigger: 'change' }]
  const epLegalPersonRule = [{ required: false, validator: validateEpLegalPerson, trigger: 'change' }]
  const getLicenseRangePlaceholderFn = () => {
    let detail = props.enterpriseDetail
    let start = detail.businessLicenseStartDate
    let end = detail.businessLicenseEndDate
    if (end) {
      end = dayjs(end).format('YYYY年MM月DD日')
    } else {
      end = '长期'
    }
    return [dayjs(start).format('YYYY年MM月DD日'), end]
  }
  const disableInputClickFn = () => {
    Message.warning('如需修改请联系客服人员')
  }
  watch(
    () => props.enterpriseDetail,
    (newVal) => {
      form.epId = newVal.epId
      form.userServiceTypes = newVal.userServiceTypes
      form.userShortRentChannels = newVal.userShortRentChannels
      form.userWxNativePay = newVal.userWxNativePay
      // 联系人，如果为空，需要补一个联系人
      let epContacts = newVal.epContacts || []
      if (epContacts && epContacts.length > 0) {
        form.epContacts = JSON.parse(JSON.stringify(epContacts))
      } else {
        form.epContacts = [{ ...defaultContacts }]
      }
    },
    { immediate: true }
  )
  const newEpContactFn = () => {
    form.epContacts.push({ ...defaultContacts })
    console.log(form.epContacts)
  }
  const delEpContactFn = (index) => {
    form.epContacts.splice(index, 1)
  }

  const formRef = ref()
  const saveFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          console.log(error)
          reject()
        } else {
          let param = {
            ...form,
          }
          let epContacts = param.epContacts
          let inputtedContacts = []
          if (epContacts.length > 0) {
            for (var i = 0; i < epContacts.length; i++) {
              var item = epContacts[i]
              let isValid = false
              for (var k in item) {
                if (item[k] && item[k] != '') {
                  isValid = true
                }
              }
              if (isValid) {
                inputtedContacts.push(item)
              }
            }
            param.epContacts = inputtedContacts
          }
          saveEnterprise(param)
            .then((res) => {
              if (res.code == 200) {
                resolve()
              }
            })
            .catch(() => {
              reject()
            })
        }
      })
    })
  }
  defineExpose({
    saveFn,
  })
</script>

<style lang="less" scoped>
  .editable-item-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 16px;
  }
  .card-item {
    width: 210px;
    height: 160px;
    border: 1px solid #e5e6eb;
    .card-item-header {
      height: 30px;
      line-height: 30px;
      background: #e5e6eb;
      font-size: 14px;
      color: #1d2129;
    }
    .card-item-content {
      padding: 5px;
      img {
        max-width: 100%;
        max-height: 100%;
      }
    }
  }
  .card-item + .card-item {
    margin-left: 16px;
  }

  .page-form-block {
    background: rgba(247, 248, 250, 0.5);
    padding: 20px 172px 0 20px;
    margin-bottom: 20px;

    .contact-item {
      position: relative;
      .operate-list {
        position: absolute;
        left: 100%;
        bottom: 20px;
        width: 154px;
        padding-left: 16px;
        .operate-btn {
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          white-space: nowrap;
          outline: none;
          cursor: pointer;
          user-select: none;
          padding: 0 12px;
          icon {
            margin-right: 8px;
          }
          &.del {
            color: #ea0000;
          }
          &.new {
            color: #165dff;
          }
        }
      }
    }
  }
</style>
